module.exports = app => {
  const router = require('express').Router({
    mergeParams: true
  })

  // 增
  router.post('/', async (req, res) => {
    await req.Model.create(req.body)
    res.send({
      success: true
    })
  })
  // 根据ID删除
  router.delete('/:id', async (req, res) => {
    await req.Model.findByIdAndDelete(req.params.id)
    res.send({
      success: true
    })
  })
  // 根据ID修改
  router.put('/:id', async (req, res) => {
    await req.Model.findByIdAndUpdate(req.params.id, req.body)
    res.send({
      success: true
    })
  })
  // 查
  router.get('/', async (req, res) => {
    const queryOptions = {}
    if (req.Model.modelName === 'Category') {
      queryOptions.populate = 'parent'
    } else if (req.Model.modelName === 'Hero') {
      queryOptions.populate = 'heroType'
    } else if (req.Model.modelName === 'Article') {
      queryOptions.populate = 'categories'
    }
    const data = await req.Model.find().setOptions(queryOptions)
    res.send(data)
  })
  // 根据ID查询
  router.get('/:id', async (req, res) => {
    const data = await req.Model.findById(req.params.id)
    res.send(data)
  })
  // 登录拦截，模块名拦截
  app.use('/admin/api/rest/:resource', require('../../middleware/auth')(), require('../../middleware/resource')(), router)
  // 登录
  require('./login')(app)
  // 上传
  require('./upload')(app)
}